#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/7/17 17:05
# @Author  : Chenmm
# @File    : test.py
# @Software: PyCharm
from config import settings
from core.Auth import create_access_token
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException

from core.Response import fail, success
from core.Utils import check_password
from models.base import User


# async def test_oath2(data: OAuth2PasswordRequestForm = Depends()):
#     '''
#     测试oauth2授权接口，未对data校验
#     :param data:
#     :return:
#     '''
#     user_type = False
#     if not data.scopes:
#         raise HTTPException(401, "请选择作用域!")
#     if "is_admin" in data.scopes:
#         user_type = True
#     jwt_data = {
#         "user_id": data.client_id,
#         "user_type": user_type
#     }
#     jwt_token = create_access_token(data=jwt_data)
#
#     return {"access_token": jwt_token, "token_type": "bearer"}


async def test_oath2(post: OAuth2PasswordRequestForm = Depends()):
    """
    用户登陆
    :param post:
    :return: jwt token
    """
    get_user = await User.get_or_none(username=post.username)
    if not get_user:
        return fail(msg=f"用户{post.username}密码验证失败!")
    if not check_password(post.password, get_user.password):
        return fail(msg=f"用户{post.username}密码验证失败!")
    if get_user.user_status != 1:
        return fail(msg=f"用户{post.username}已被管理员禁用!")
    jwt_data = {
        "user_id": get_user.pk,
        "user_type": get_user.user_type
    }
    jwt_token = create_access_token(data=jwt_data)
    return {"access_token": jwt_token, "token_type": "bearer", "expires_in": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60}
